package com.zxj.friend.service.user.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zxj.common.core.contains.Constants;
import com.zxj.common.core.domain.qo.PageQuery;
import com.zxj.common.core.domain.vo.PageVO;
import com.zxj.common.core.utils.ThreadLocalUtil;
import com.zxj.friend.domain.message.entity.Message;
import com.zxj.friend.domain.message.vo.MessageTextVO;
import com.zxj.friend.manager.MessageCacheManager;
import com.zxj.friend.mapper.message.MessageMapper;
import com.zxj.friend.mapper.message.MessageTextMapper;
import com.zxj.friend.service.user.IUserMessageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


@Service
@Slf4j
public class UserMessageServiceImpl implements IUserMessageService {

    @Autowired
    private MessageCacheManager messageCacheManager;

    @Autowired
    private MessageTextMapper messageTextMapper;

    @Autowired
    private MessageMapper messageMapper;

    /**
     * 分页获取用户消息列表
     * @param pageQuery 分页查询参数
     * @return PageVO<MessageTextVO>
     */
    @Override
    public PageVO<MessageTextVO> pageList(PageQuery pageQuery) {
        Long userId = ThreadLocalUtil.get(Constants.USER_ID, Long.class);
        Long total = messageCacheManager.getListSize(userId);
        List<MessageTextVO> messageTextVOList;
        if (total == null || total <= 0) { //缓存中没有数据
            //从数据库中查询我的竞赛列表
            PageHelper.startPage(pageQuery.getPageNo(), pageQuery.getPageSize());
            messageTextVOList = messageTextMapper.selectUserMsgList(userId);
            // 刷新缓存
            messageCacheManager.refreshCache(userId);
            total = new PageInfo<>(messageTextVOList).getTotal();
        } else {
            messageTextVOList = messageCacheManager.getMsgTextVOList(pageQuery, userId);
        }
        if (CollectionUtil.isEmpty(messageTextVOList)) {
            return PageVO.empty();
        }
        return PageVO.of(messageTextVOList, total);
    }

    /**
     * 删除消息
     * @param textId 消息id
     * @return 成功与否
     */
    @Override
    @Transactional
    public int deleteMessage(Long textId) {
        Long userId = ThreadLocalUtil.getUserId();
        // 1. 先删除缓存中的数据
        messageCacheManager.deleteMessageCache(userId, textId);

        // 2. 删除数据库中的数据
        // 删除消息列表
        Db.remove(new LambdaQueryWrapper<>(Message.class)
                .eq(Message::getTextId, textId)
                .eq(Message::getRecId, userId)
                .eq(Message::getSendId, Constants.SYSTEM_USER_ID));
        // 删除消息详情
        return messageTextMapper.deleteById(textId) ;
    }
}
